package com.lsa.letcode.the116.populateNextRight;

import com.lsa.letcode.common.TreeLinkNode;

/**
 * Definition for binary tree with next pointer.
 * public class TreeLinkNode {
 *     int val;
 *     TreeLinkNode left, right, next;
 *     TreeLinkNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void connect(TreeLinkNode root) {
    	while(root != null){
    		TreeLinkNode nextLevel = root.left;
    		TreeLinkNode parent = root;
    		do{
    			if (parent.left != null){
    				parent.left.next = parent.right;
    			}
    			
    			if (parent.right != null && parent.next != null){
    				parent.right.next = parent.next.left;
    			}
    			
    			parent = parent.next;
    		}
    		while(parent != null);
    		root = nextLevel;
    	}
    }
}